package com.spring.demo.redis.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class RedissonConfig {
    @Autowired
    private RedissonProperties redissonProperties;

    // 哨兵模式自动装配
    @Bean
    RedissonClient redissonSentinel() {
        Config config = new Config();

        String[] nodes = redissonProperties.getSentinelAddresses();
        List<String> newNodes = new ArrayList(nodes.length);
        Arrays.stream(nodes).forEach((index) -> newNodes.add(
                index.startsWith("redis://") ? index : "redis://" + index));
        // addSentinelAddress("redis://106.15.74.61:26381","redis://106.15.74.61:26380","redis://106.15.74.61:26379")
        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(newNodes.toArray(new String[0]))
                // sentinel monitor myredis 127.0.0.1 6379 1
                // .setMasterName("myredis")
                .setMasterName(redissonProperties.getMasterName())
                .setTimeout(redissonProperties.getTimeout())
                .setMasterConnectionPoolSize(redissonProperties.getMasterConnectionPoolSize())
                .setSlaveConnectionPoolSize(redissonProperties.getSlaveConnectionPoolSize());
        return Redisson.create(config);
    }


    //单机模式自动装配
/*    @Bean
    RedissonClient redissonSingle() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                //.setAddress("redis://106.15.74.61:6380")
                .setAddress(redissonProperties.getAddress())
                .setTimeout(redissonProperties.getTimeout())
                .setConnectionPoolSize(redissonProperties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(redissonProperties.getConnectionMinimumIdleSize());

        return Redisson.create(config);
    }*/

    /**
     * 集群模式的 redisson 客户端
     *
     * @return
     */
    /*@Bean
    RedissonClient redissonCluster() {

    }*/


}
